#include "devicemanager.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>

DeviceManager::DeviceManager(QObject *parent)
    : QObject(parent)
    , m_statusCheckTimer(new QTimer(this))
    , m_allInitialized(false)
    , m_connectedDevices(0)
    , m_totalDevices(3)
{
    // 初始化设备名称映射 - 只保留实际存在的设备
    m_deviceNames[NetworkDisplay1] = "网络显示屏1";
    m_deviceNames[NetworkDisplay2] = "网络显示屏2";
    m_deviceNames[AudioDevice] = "音频设备";
    
    // 初始化所有设备状态为未知
    for (auto it = m_deviceNames.begin(); it != m_deviceNames.end(); ++it) {
        m_deviceStatus[it.key()] = Unknown;
    }
    
    // 设置状态检查定时器
    m_statusCheckTimer->setInterval(5000); // 每5秒检查一次
    connect(m_statusCheckTimer, &QTimer::timeout, this, &DeviceManager::performStatusCheck);
    
    qDebug() << "设备管理器初始化完成，管理" << m_totalDevices << "个设备";
}

DeviceManager::~DeviceManager()
{
    if (m_statusCheckTimer->isActive()) {
        m_statusCheckTimer->stop();
    }
}

void DeviceManager::initializeDevices()
{
    qDebug() << "开始初始化所有设备...";
    
    m_connectedDevices = 0;
    
    // 逐个初始化设备
    for (auto it = m_deviceNames.begin(); it != m_deviceNames.end(); ++it) {
        initializeDevice(it.key());
    }
    
    // 启动状态监控
    m_statusCheckTimer->start();
    
    qDebug() << "设备初始化完成，已连接" << m_connectedDevices << "/" << m_totalDevices << "个设备";
    
    if (m_connectedDevices == m_totalDevices) {
        m_allInitialized = true;
        emit allDevicesReady();
    }
}

void DeviceManager::initializeDevice(DeviceType type)
{
    setDeviceStatus(type, Initializing);
    
    DeviceStatus status = checkDevice(type);
    setDeviceStatus(type, status);
    
    if (status == Connected) {
        m_connectedDevices++;
        // qDebug() << m_deviceNames[type] << "初始化成功"; // 仅在需要时启用
    } else {
        qWarning() << m_deviceNames[type] << "初始化失败"; // 保留失败警告
        emit deviceError(type, m_deviceNames[type] + "初始化失败");
    }
}

DeviceManager::DeviceStatus DeviceManager::checkDevice(DeviceManager::DeviceType type)
{
    switch (type) {
    case NetworkDisplay1:
        // 检查网络显示设备1（通过网络连接状态）
        // 这里可以检查网络连接或ping设备IP
        return Connected;
        
    case NetworkDisplay2:
        // 检查网络显示设备2（通过网络连接状态）
        // 这里可以检查网络连接或ping设备IP
        return Connected;
        
    case AudioDevice:
        // 检查音频设备
        if (QFileInfo::exists("/proc/asound/cards")) {
            return Connected;
        }
        break;
    }
    
    // 如果硬件文件不存在，在开发环境中模拟为已连接
    qDebug() << "模拟模式：" << m_deviceNames[type] << "已连接";
    return Connected;
}

void DeviceManager::setDeviceStatus(DeviceType type, DeviceStatus status)
{
    if (m_deviceStatus[type] != status) {
        DeviceStatus oldStatus = m_deviceStatus[type];
        m_deviceStatus[type] = status;
        
        QString statusText;
        switch (status) {
        case Unknown: statusText = "未知"; break;
        case Connected: statusText = "已连接"; break;
        case Disconnected: statusText = "已断开"; break;
        case Error: statusText = "错误"; break;
        case Initializing: statusText = "初始化中"; break;
        }
        
        // qDebug() << m_deviceNames[type] << "状态变化:" << statusText; // 可选调试
        emit deviceStatusChanged(type, status);
        
        // 更新连接设备计数
        if (oldStatus == Connected && status != Connected) {
            m_connectedDevices--;
        } else if (oldStatus != Connected && status == Connected) {
            m_connectedDevices++;
        }
    }
}

void DeviceManager::checkDeviceStatus()
{
    // qDebug() << "执行设备状态检查..."; // 过于频繁，已禁用
    
    for (auto it = m_deviceNames.begin(); it != m_deviceNames.end(); ++it) {
        DeviceType type = it.key();
        DeviceStatus currentStatus = m_deviceStatus[type];
        
        if (currentStatus != Initializing) {
            DeviceStatus newStatus = checkDevice(type);
            setDeviceStatus(type, newStatus);
        }
    }
    
    // qDebug() << "状态检查完成，连接设备:" << m_connectedDevices << "/" << m_totalDevices; // 过于频繁，已禁用
}

void DeviceManager::performStatusCheck()
{
    checkDeviceStatus();
}

void DeviceManager::reconnectDevice(DeviceType type)
{
    qDebug() << "尝试重新连接设备:" << m_deviceNames[type];
    
    setDeviceStatus(type, Initializing);
    
    // 模拟重连延时
    QTimer::singleShot(1000, [this, type]() {
        DeviceStatus status = checkDevice(type);
        setDeviceStatus(type, status);
        
        if (status == Connected) {
            // qDebug() << m_deviceNames[type] << "重连成功";
        } else {
            qWarning() << m_deviceNames[type] << "重连失败";
            emit deviceError(type, m_deviceNames[type] + "重连失败");
        }
        
        // 发射连接状态变化信号
        bool allConnected = (m_connectedDevices == m_totalDevices);
        emit deviceConnectionChanged(allConnected);
    });
}

void DeviceManager::reconnectDevices()
{
    qDebug() << "尝试重新连接所有设备...";
    
    for (auto it = m_deviceNames.begin(); it != m_deviceNames.end(); ++it) {
        DeviceType type = it.key();
        if (m_deviceStatus[type] != Connected) {
            reconnectDevice(type);
        }
    }
    
    // 延时后检查整体连接状态
    QTimer::singleShot(2000, [this]() {
        bool allConnected = (m_connectedDevices == m_totalDevices);
        emit deviceConnectionChanged(allConnected);
        // qDebug() << "设备重连完成，连接状态:" << (allConnected ? "全部连接" : "部分连接"); // 过于频繁，已禁用
    });
}

void DeviceManager::resetDevice(DeviceType type)
{
    qDebug() << "重置设备:" << m_deviceNames[type];
    
    setDeviceStatus(type, Initializing);
    
    // 根据设备类型执行特定的重置操作
    switch (type) {
    case NetworkDisplay1:
    case NetworkDisplay2:
        // 网络显示屏重置
        break;
        
    case AudioDevice:
        // 音频设备重置
        break;
    }
    
    // 模拟重置延时
    QTimer::singleShot(2000, [this, type]() {
        DeviceStatus status = checkDevice(type);
        setDeviceStatus(type, status);
        
        if (status == Connected) {
            qDebug() << m_deviceNames[type] << "重置成功";
        } else {
            qWarning() << m_deviceNames[type] << "重置失败";
            emit deviceError(type, m_deviceNames[type] + "重置失败");
        }
    });
} 